package com.wei.service_oss.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wei.service_oss.service.OssService;
import com.wei.service_oss.util.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author wjx
 * @ClassName OssServiceImpl
 * @description: TODO
 * @date 2022-11-28 18:34
 * @version: 1.0
 */
@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadAvatar(MultipartFile file) {

        // Endpoint
        String endpoint = ConstantPropertiesUtil.ENDPOINT;

        // 阿里云账号AccessKey
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;

        // 填写Bucket名称
        String bucketName = ConstantPropertiesUtil.BUCKET;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = null;
        //要返回的图片地址
        String url = "";
        try {
            //1.文件名保持唯一
            String fileName = UUID.randomUUID().toString(true) + file.getOriginalFilename();

            inputStream = file.getInputStream();

            //2.把文件按照日期进行分类
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //现在的文件：2022/07/15/uuidgirl.jpg
            String finalName = datePath + "/" + fileName;

            //ossClient.putObject(Bucket名称,上传到oss文件路径和文件名称,上传文件输入流)
            ossClient.putObject(bucketName, finalName, inputStream);


            //路径：https://guli-parent-bucket100.oss-cn-hangzhou.aliyuncs.com/2.jpg
            url = "https://" + bucketName + "." + endpoint + "/" + finalName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            if (inputStream != null) {
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return url;
    }
}
